import React, { memo, useEffect, useState } from 'react'
import classNames from 'classnames'
import './style.less'
import { Button, Col, Flex, Row } from 'antd'
import { HsAdminInput, HsAdminPage, HsAdminSpin, HsAdminTablePage } from '@hs-admin/base-components'
import { usePage } from '@hs-admin/utils'
import { HsAdminDataItemDetailModal } from '@hs-admin/components'
import { getProductCategoryList } from '@/api/assetMaintain/dataProduct'
import { getProductItemSetList } from '@/api/assetMaintain/dataProduct/item_set'
import { getProductWebsiteList } from '@/api/assetMaintain/dataProduct/website'
import { useNavigate } from 'react-router-dom'

interface Props {
  source: 'item_set' | 'website'
}
const ThemeDetail: React.FC<Props> = (props: Props) => {
  const { source } = props
  const [choseTag, setchoseTag] = useState('全部') // 选择的主题id
  const [topicList, settopicList] = useState<any[]>([])
  const [searchValue, setsearchValue] = useState<string>('')
  const { pagination, resetPage, initPage } = usePage(getChildList)
  const [dataItemId, setdataItemId] = useState('')
  const navigate: any = useNavigate()
  const [choseTopicName, setchoseTopicName] = useState('全部')
  const [choseTopicDes, setchoseTopicDes] = useState('')

  const columns: any[] = [
    {
      title: '产品名称',
      dataIndex: 'name'
    },
    {
      title: '产品描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '类别',
      dataIndex: source === 'item_set' ? 'item_set_tag.name' : 'website_tag.name'
    },
    {
      title: '最新编辑用户',
      dataIndex: 'owner.name'
    },
    {
      title: '最新维护时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    }
  ]
  if (source === 'item_set') {
    columns.push({
      title: '操作',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <>
          <Button
            type="link"
            size="small"
            onClick={() => {
              navigate(`/marketBasicData/themeDetail?id=${record.id}&source=product`)
            }}>
            详情
          </Button>
        </>
      )
    })
  }
  const [data, setdata] = useState<any[]>([])
  const [loading, setloading] = useState(true)

  // 点击
  const handleTopicClick = (item: any) => {
    setchoseTag(item.name)
    setchoseTopicName(item.name)
    setchoseTopicDes(item.description)
    resetPage()
  }
  // 获取列表
  async function getChildList() {
    setloading(true)
    setdata([])
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keywords: searchValue || undefined,
      tags: choseTag === '全部' ? undefined : choseTag
    }
    let callFn = getProductItemSetList
    if (source === 'website') {
      callFn = getProductWebsiteList
    }
    return callFn(params).then((res) => {
      const dataList = res.items
      setdata(dataList)
      setloading(false)
      return res
    })
  }
  // 搜索按钮
  const handleSearchClick = () => {
    initPage()
    getChildList()
  }

  useEffect(() => {
    getProductCategoryList({ page_size: 999, category: source }).then((res) => {
      res.items.unshift({ name: '全部', id: null })
      settopicList(res.items)
    })
  }, [])

  return (
    <div className="market-item-set-website-detail">
      {loading && <HsAdminSpin />}
      <div className="top">
        {topicList.map((item, index) => (
          <div className={classNames('top_item', { isActive: item.name === choseTag })} key={index} onClick={() => handleTopicClick(item)}>
            {item.name}
          </div>
        ))}
      </div>

      <div className="mid">
        <div className="mid_title">
          <div>{choseTopicName}</div>
        </div>

        <div className="my-4 break-words">{choseTopicDes}</div>

        <Flex align="center" gap={'middle'}>
          <Flex align="center" gap={'small'}>
            <span className="flex-none">产品名称：</span>
            <HsAdminInput
              defaultValue={searchValue}
              placeholder="请输入产品名称"
              allowClear
              onChange={(e: { target: { value: React.SetStateAction<string> } }) => setsearchValue(e.target.value)}
              className="min-w-md"
              onPressEnter={(e: { target: { value: React.SetStateAction<string> } }) => {
                setsearchValue(e.target.value)
                handleSearchClick()
              }}
            />
            <Button type="primary" onClick={handleSearchClick}>
              搜索
            </Button>
          </Flex>
        </Flex>
        <br />
        {source === 'item_set' && (
          <HsAdminTablePage id="J_theme_detail_view" columns={columns} rowKey="id" dataSource={data} pagination={pagination} size="small" />
        )}
        {source === 'website' && (
          <>
            <Row gutter={[12, 12]}>
              {data.map((item) => (
                <Col
                  span={6}
                  key={item.id}
                  onClick={() => {
                    window.open(item.url, '_blank')
                  }}>
                  <div className="grid-item">
                    <Flex align="center" justify="space-between">
                      <h3 className="font-bold break-words">{item.name}</h3>
                    </Flex>
                    <p className="show-text" title={item.description}>
                      {item.description}
                    </p>
                  </div>
                </Col>
              ))}
            </Row>
            <Flex justify="flex-end" className="mt-4">
              <HsAdminPage {...pagination} />
            </Flex>
          </>
        )}
      </div>
      <HsAdminDataItemDetailModal id={dataItemId} onCancel={() => setdataItemId('')} />
    </div>
  )
}

export default memo(ThemeDetail)
